import 'dart:async';
import 'dart:io';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_account.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/account_security_mixin.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/web_view_mixin.dart';
import 'package:inmotion_pro/pages/models/user_model.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:inmotion_pro/service/guest_service.dart';
import 'package:inmotion_pro/service/log_service.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/alert/agreement_dialog.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'state.dart';

enum AuthMode { emailLogin, emailRegister, phoneLogin, forgotPassword }

// 登陆控制器
class LoginRegisterController extends GetxController
    with WebViewMixin, AccountSecurityMixin, CacheMixin {
  // 状态
  final LoginRegisterState state = LoginRegisterState();

  @override
  Future<void> onInit() async {
    super.onInit();

    // 检查用户是否同意用户协议与隐私政策
    _showIfNeededAgreementDialog();
    state.phoneCode.value = GlobalService.to.phoneCode.value;
  }

  // 检查用户是否同意用户协议与隐私政策
  _showIfNeededAgreementDialog() async {
    final agreedToTerms = await AgreementDialog.showIfNeeded(
      Get.context!,
      dialog: AgreementDialog(
        onDisagree: () {
          if (Platform.isAndroid) {
            // 如果用户不同意则退出应用
            SystemNavigator.pop();
          } else if (Platform.isIOS) {
            // iOS平台闪退
            _crashIOS();
          }
        },
        userAgreementOnTap: () {
          webViewMixinPushTo(WebViewUrlType.userAgreement);
        },
        privacyPolicyOnTap: () {
          webViewMixinPushTo(WebViewUrlType.privacyPolicy);
        },
      ),
    );
    if (agreedToTerms) {
      debugPrint('用户同意了协议');
    }
  }

  // iOS平台闪退
  Future<void> _crashIOS() async {
    try {
      const platform = MethodChannel('crash_channel');
      await platform.invokeMethod('crash');
    } catch (e) {
      debugPrint("调用崩溃失败: $e");
    }
  }

  // 发送验证码
  Future<bool> requestVerificationCode({
    required String account,
    required CodePlatform platform,
    required CodeType codeType,
    String? securityToken,
    Map<String, String>? tokenMap,
  }) {
    return accountSecurityRequestVerificationCode(
      account: account,
      platform: platform,
      codeType: codeType,
      securityToken: securityToken,
      tokenMap: tokenMap,
    );
  }

  // 邮箱注册
  void emailRegister({
    required String email,
    required String password,
    required String code,
  }) {
    Loading.showLoading(null);
    // 先校验验证码，再注册
    ApiHelper()
        .verifyVerificationCode(
            account: email,
            platform: CodePlatform.email,
            codeType: CodeType.register,
            code: code)
        .then((verifytoken) {
      return ApiHelper().emailRegister(
        email: email,
        password: password,
        verifyToken: verifytoken,
      );
    }).then((responseModel) {
      _loginOrRegisterSuccess(responseModel.toMap());
    }).catchErrorHandler();
  }

  // 邮箱/手机号登录
  void accountLogin({
    String? name,
    String? email,
    String? phone,
    String? password,
    String? code,
  }) {
    Loading.showLoading(null);
    ApiHelper()
        .login(
            name: name,
            email: email,
            phone: phone,
            password: password,
            code: code)
        .then((responseModel) {
      _loginOrRegisterSuccess(responseModel.toMap());
    }).catchErrorHandler();
  }

  // 邮箱重置密码
  Future<bool> emailResetPassword({
    required String email,
    required String password,
    required String code,
  }) {
    Loading.showLoading(null);
    // 先校验验证码，再注册
    return ApiHelper()
        .verifyVerificationCode(
            account: email,
            platform: CodePlatform.email,
            codeType: CodeType.resetPwd,
            code: code)
        .then((securityToken) {
      return ApiHelper().resetPassword(
        email: email,
        password: password,
        securityToken: securityToken,
      );
    });
  }

  // 第三方登陆
  thirdLogin() {
    Auth3rdType auth3rdType =
        Platform.isAndroid ? Auth3rdType.google : Auth3rdType.apple;
    // 登陆
    accountSecurity3rdLogin(auth3rdType, onSuccess: (auth3rdModel) {
      Loading.showLoading(null);
      ApiHelper()
          .login(auth3rdModel: auth3rdModel..auth3rdType = auth3rdType)
          .then((responseModel) {
        _loginOrRegisterSuccess(responseModel.toMap());
      }).catchErrorHandler();
    }, onError: () {});
  }

  // 登录或注册成功
  _loginOrRegisterSuccess(Map<String, dynamic> userMap) async {
    Loading.showSuccess(local.login_success);
    debugPrint("登录或注册成功: $userMap");
    UserModel userModel = UserModel.fromMap(userMap);
    cacheMixinAddUser(userModel
          ..token = userModel.token
          ..isSelected = true)
        .then((_) async {
      if (userModel.uid != 0) {
        // 更新缓存中的用户信息
        await cacheMixinUpdateUser(
          userModel.uid,
          token: userModel.token,
          isSelected: true,
        );
        // 跳转到车辆页面
        LogService.to.info("【$runtimeType】登陆成功");
        Get.offAllNamed(AppRoutes.ROOT);
      } else {
        LogService.to.error("【$runtimeType】登陆失败");
        LxToast.show(local.login_failed);
      }
    }).catchError((e) {
      LogService.to.error("【$runtimeType】登陆失败: $e");
      LxToast.show(local.login_failed);
    });
  }

  // 游客登陆
  guestLoginButtonOnTap() async {
    GuestService.to.enterGuestMode().then((_) {
      Get.toNamed(AppRoutes.ROOT);
      // 如果在 Get.toNamed(AppRoutes.ROOT)?.then 里响应函数里，退出游客模式，会出现页面闪烁问题
      // 所以在MainPage里，@override Future<void> onClose() 的super.onClose()之前，处理退出游客模式
    }).catchErrorHandler();
  }
}
